package com.situ.crm.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.situ.crm.common.exception.BusinessException;
import com.situ.crm.common.util.SessionUtil;
import com.situ.crm.entity.Menu;
import com.situ.crm.entity.User;
import com.situ.crm.mapper.MenuMapper;
import com.situ.crm.service.IMenuService;
import com.situ.crm.vo.MenuVO;
import com.situ.crm.vo.NavbarVO;
import com.situ.crm.vo.ResultDataVO;

@Service("menuService")
public class MenuServiceImpl implements IMenuService {

	@Autowired
	private MenuMapper menuMapper;

	@Override
	public List<NavbarVO> selectMenuList() {
		User user = SessionUtil.getCurrentUser();
		// 取出当前用户有权限的菜单的ID集合
//		List<Integer> menuIDs = roleMenuMapper.selectMenuByUserId(user.getId());
		List<NavbarVO> list = menuMapper.selectAllMenus(user.getId());
//		List<NavbarVO> newList = new ArrayList<>();
//		long l = System.currentTimeMillis();
//		for (NavbarVO vo : list) {
//			if (menuIDs.contains(vo.getId())) {
//				List<NavbarVO> subList = new ArrayList<>();
//				for (NavbarVO sub : vo.getChildren()) {
//					if (menuIDs.contains(sub.getId())) {
//						subList.add(sub);
//					}
//				}
//				vo.setChildren(subList);
//				newList.add(vo);
//			}
//		}
//		System.out.println("双层for执行时间" + (System.currentTimeMillis() - l));
//		
		return list;
	}

	@Override
	public ResultDataVO selectMenuPage(String name, Integer page, Integer limit) {
		ResultDataVO result = new ResultDataVO();
		PageHelper.startPage(page, limit);
		List<Menu> list = menuMapper.selectMenus(name);
		result.setData(list);
		PageInfo<Menu> pageInfo = new PageInfo<>(list);
		result.setCount(pageInfo.getTotal());
		return result;
	}

	@Override
	public List<Menu> selectTops() {
		return menuMapper.selectByParentId(0);
	}

	@Override
	public void doSave(Menu menu) {
		if (menu.getId() == null) {
			menuMapper.insert(menu);
		} else {
			menuMapper.updateByPrimaryKey(menu);
		}
	}

	@Override
	public void doDel(Integer id) {
		List<Menu> subList = menuMapper.selectByParentId(id);
		if (subList != null && !subList.isEmpty()) {// 说明要删除的这个菜单是有子菜单的，不让删除
			throw new BusinessException("menu.del", "包含子菜单，不能删除！！！！！");
		}
		menuMapper.deleteByPrimaryKey(id);
	}

	@Override
	public Menu selectById(Integer id) {
		return menuMapper.selectByPrimaryKey(id);
	}

	@Override
	public List<MenuVO> selectMenuTree(Integer roleId) {
		List<MenuVO> list = new ArrayList<>();
		list = menuMapper.selectMenuTree(roleId);
		return list;
	}
}
